<template>
    <div class="goods-add-container">

        <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
                <el-page-header @back="goback" content="商品基本信息">
                </el-page-header>
            </div>

            <el-form :model="form" :rules="rules" ref="form" label-width="140px">
                <!-- 商品名称 -->
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入商品名称" style="width: 500px"></el-input>
                </el-form-item>

                <!-- 商品分类 -->
                <el-form-item label="商品分类" prop="category_id">
                    <el-select v-model="form.category_id" placeholder="请选择商品分类" style="width: 500px">
                        <el-option v-for="i in categoryList" :label="i.name" :value="i.id" :key="i.id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 商品价格 -->
                <el-row style="width: 900px">
                    <el-col :span="8">
                        <el-form-item label="商品价格" prop="price">
                            <el-input type="number" v-model="form.price" controls-position="right"
                                placeholder="请输入价格"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="是否推荐" prop="is_recommend">
                            <el-select v-model="form.is_recommend" placeholder="请选择是否限时商品">
                                <el-option label="是" :value="1"></el-option>
                                <el-option label="否" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="商品折扣价" prop="discount_price">
                            <el-input type="number" v-model="form.discount_price" :min="0" controls-position="right"
                                placeholder="请输入商品折扣价"></el-input>
                        </el-form-item> -->
                    </el-col>
                </el-row>
                <!-- 商品库存 -->
                <el-row style="width: 900px">
                    <el-col :span="8">
                        <el-form-item label="商品库存" prop="stock">
                            <el-input type="number" v-model="form.stock" :min="0" controls-position="right"
                                placeholder="请输入商品库存"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商品状态" prop="status">
                            <el-select v-model="form.status" placeholder="请选择商品状态">
                                <el-option label="在售" :value="1"></el-option>
                                <el-option label="下架" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 是否优惠商品 -->
                <el-row style="width: 900px">
                    <el-col :span="8">
                        <el-form-item label="是否优惠" prop="is_discount">
                            <el-select v-model="form.is_discount" placeholder="请选择商品状态">
                                <el-option label="优惠" :value="1"></el-option>
                                <el-option label="原价" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商品优惠价格" prop="discount_price">
                            <el-input type="number" v-model="form.discount_price" :min="0" controls-position="right"
                                placeholder="请输入价格"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 是否限时商品 -->
                <el-row style="width: 900px">
                    <el-col :span="8">
                        <el-form-item label="是否限时" prop="is_flash_sale">
                            <el-select v-model="form.is_flash_sale" placeholder="请选择是否限时商品">
                                <el-option label="是" :value="1"></el-option>
                                <el-option label="否" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="限时折扣价" prop="flash_sale_price">
                            <el-input type="number" v-model="form.flash_sale_price" :min="0" controls-position="right"
                                placeholder="请输入价格"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 是否限时时段 -->
                <el-form-item label="限时时间" prop="timeRange">
                    <el-date-picker v-model="form.timeRange" type="datetimerange" range-separator="至"
                        start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss"
                        style="width: 400px"></el-date-picker>
                </el-form-item>

                <!-- 限时商品下单间隔天数 -->
                <!-- <el-form-item label="下单间隔天数" prop="flash_sale_purchase_interval">
                    <el-input style="width: 500px;" type="number" v-model="form.flash_sale_purchase_interval" :min="0"
                        controls-position="right" placeholder="请输入限时商品下单间隔天数"></el-input>
                </el-form-item> -->

                <!-- 商品排序 -->
                <el-form-item label="商品排序" prop="sort">
                    <el-input style="width: 500px;" type="number" v-model="form.sort" :min="0" controls-position="right"
                        placeholder="请输入商品排序"></el-input>
                </el-form-item>
                <!-- 商品描述 -->
                <!-- <el-form-item label="商品描述" prop="description">
                    <el-input type="textarea" v-model="form.description" :rows="3" placeholder="请输入商品描述"
                        style="width: 500px"></el-input>
                </el-form-item> -->


                <!-- 商品主图 -->
                <el-form-item label="商品主图" prop="main_image">
                    <el-upload class="avatar-uploader" action="https://api.tianxinghuayi.cn/upload"
                        :show-file-list="false" :on-success="handleMainImageSuccess" :before-upload="beforeImageUpload">
                        <img v-if="form.main_image" :src="form.main_image | filter_img" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div class="upload-tip">建议尺寸：800x800像素，大小不超过2MB</div>
                </el-form-item>

                <!-- 商品轮播图 -->
                <el-form-item label="商品轮播图" prop="images">
                    <el-upload action="https://api.tianxinghuayi.cn/upload" list-type="picture-card"
                        :file-list="form.images" :on-success="handleSliderSuccess" :on-remove="handleRemoveSlider"
                        :before-upload="beforeImageUpload" :limit="5">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div class="upload-tip">最多上传5张图片，每张大小不超过2MB</div>
                </el-form-item>

                <!-- 提交按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="submitForm">提交</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import { IMG_URL } from '@/utils/utils';
import { goodsAdd, goodsCategoryList, goodsEdit, getGoodsDetails } from '../api';

export default {
    name: 'GoodsAdd',
    data() {
        return {
            form: {
                name: '',
                category_id: null,
                price: null,
                stock: 999999,
                main_image: '',
                images: [],
                description: '',
                status: 1,
                sort: null,
                is_discount: 0,
                discount_price: null,
                is_flash_sale: 0,
                flash_sale_price: null,
                flash_sale_start_time: 0,
                flash_sale_end_time: 0,
                // flash_sale_purchase_interval: null,
                timeRange: [],
                is_recommend: 0,
            },
            rules: {
                name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                main_image: [
                    { required: true, message: '请上传商品主图', trigger: 'blur' }
                ],
                images: [
                    { required: true, message: '请上传商品轮播图', trigger: 'blur' }
                ],
                category_id: [
                    { required: true, message: '请选择商品分类', trigger: 'change' }
                ],
                price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' },
                ],
                is_discount: [
                    { required: true, message: '请选择商品是否为优惠商品', trigger: 'change' }
                ],
                stock: [
                    { required: true, message: '请输入商品库存', trigger: 'blur' },
                ],
                status: [
                    { required: true, message: '请选择商品状态', trigger: 'change' }
                ],
                is_flash_sale: [
                    { required: true, message: '请选择商品是否为限时商品', trigger: 'change' }
                ],
                is_recommend: [
                    { required: true, message: '请选择商品是否推荐', trigger: 'change' }
                ],
                // flash_sale_purchase_interval: [
                //     { required: true, message: '请输入下单间隔天数', trigger: 'blur' },
                // ],
                // sort: [
                //     { required: true, message: '请输入商品排序', trigger: 'blur' },
                // ],
            },
            merchantId: null,
            categoryList: [],
        }
    },
    created() {

        // let id = window.location.href.split('=')[1];
        this.merchantId = this.$route.query && this.$route.query.id;
        goodsCategoryList({ page: 1, page_size: 9999, merchant_id: this.merchantId }).then(res => {
            const arr = res.data || res.list;
            this.categoryList = arr.sort((a,b)=>a.sort-b.sort);
        })
        if (this.$route.query && this.$route.query.currentItemId) {
            getGoodsDetails({ id: this.$route.query.currentItemId }).then(res => {
                this.form = { ...res }
                // 限时时间字段
                if (res.flash_sale_start_time && res.flash_sale_end_time) {
                    this.form.timeRange = [res.flash_sale_start_time, res.flash_sale_end_time]
                }
                // 轮播图字段
                let imgResArr = []
                res.images.split(',').forEach(path => {
                    imgResArr.push({
                        path: path,
                        url: IMG_URL + path,
                        name: ''
                    })
                })
                this.form.images = imgResArr || []
            })
        }
    },
    methods: {
        goback() {
            this.$router.go(-1)
        },
        // 主图上传成功
        handleMainImageSuccess(res, file) {
            this.form.main_image = res.data.path
        },

        // 轮播图上传成功
        handleSliderSuccess(res, file) {
            this.form.images.push({
                path: res.data.path,
                url: IMG_URL + res.data.path,
                name: file.name
            })
        },

        // 删除轮播图
        handleRemoveSlider(file, fileList) {
            this.form.images = fileList
        },

        // 图片上传前校验
        beforeImageUpload(file) {
            const isImage = file.type.includes('image/')
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isImage) {
                this.$message.error('只能上传图片文件!')
            }
            if (!isLt2M) {
                this.$message.error('图片大小不能超过 2MB!')
            }

            return isImage && isLt2M
        },

        // 提交表单
        submitForm() {
            console.log('this.form', this.form.images.map(i => i.path));

            this.$refs.form.validate(valid => {
                if (valid) {
                    // 这里应该是实际的上传逻辑
                    console.log('提交数据:', this.form,)
                    const p = {
                        ...this.form,
                        merchant_id: this.merchantId,
                        flash_sale_start_time: this.form.timeRange ? this.form.timeRange[0] : null,
                        flash_sale_end_time: this.form.timeRange ? this.form.timeRange[1] : null,
                        images: this.form.images.map(i => i.path),
                    }
                    if (this.$route.query && this.$route.query.currentItemId) {
                        // goodsEdit
                        goodsEdit(p).then(res => {
                            this.$message.success('商品编辑成功!')
                            this.resetForm();
                            this.goback();
                        })
                    } else {
                        goodsAdd(p).then(res => {
                            this.$message.success('商品添加成功!')
                            this.resetForm();
                            this.goback();
                        }).catch(() => {

                        })
                    }


                } else {
                    this.$message.error('请填写完整信息!')
                    return false
                }
            })
        },

        // 重置表单
        resetForm() {
            this.$refs.form.resetFields()
            this.form.main_image = '';
            this.form.images = [];
            this.form.timeRange = []
        }
    }
}
</script>

<style lang="scss" scoped>
.clearfix {
    display: flex;
    align-items: center;
}

.goods-add-container {
    padding: 20px;

    .box-card {
        border-radius: 4px;

        ::v-deep .el-card__header {
            border-bottom: 1px solid #f0f0f0;
            padding: 15px 20px;
            font-weight: bold;
        }
    }

    .upload-tip {
        font-size: 12px;
        color: #999;
        margin-top: 7px;
    }

    .avatar-uploader {
        ::v-deep .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            width: 150px;
            height: 150px;

            &:hover {
                border-color: #409EFF;
            }
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 150px;
            height: 150px;
            line-height: 150px;
            text-align: center;
        }

        .avatar {
            width: 150px;
            height: 150px;
            display: block;
            object-fit: cover;
        }
    }

    ::v-deep .el-upload-list--picture-card .el-upload-list__item {
        width: 100px;
        height: 100px;
    }

    ::v-deep .el-upload--picture-card {
        width: 100px;
        height: 100px;
        line-height: 100px;
    }
}
</style>
